package com.maben.udp.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * netty自定义处理器
 **/
@Component
public class SocketHandler extends ChannelInboundHandlerAdapter {
    private AtomicLong num = new AtomicLong(0);

    /**
     * 通道读取，因为这里使用的是【NioDatagramChannel.class】不用给发送端响应
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final DatagramPacket packet = (DatagramPacket) msg;
        final ByteBuf buf = packet.content();
        System.out.println(num.addAndGet(1)+"server receive msg: " + buf.toString(CharsetUtil.UTF_8));
    }


    /**
     * 连接成功后，自动执行该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("connect success!");
    }

    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}